<?php
namespace App\Http\Controllers\Api\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Api\Controller;
use App\Core\Entity\Cookie\UserEntity as CookieUserEntity;
use App\Core\Entity\Cookie\LocationEntity as CookieLocationEntity;
use App\Services\Base\DistrictService;

class IndexController extends Controller
{

    /**
     * 获取用户登录信息
     */
    public function getSign()
    {
        $data = (new CookieUserEntity($this->identity()))->getArrayCopy();
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 获取定位地址信息
     */
    public function getLocation()
    {
        $data = (new CookieLocationEntity($this->location()))->getArrayCopy();
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 保存定位地址
     *
     * @param $id 必选            
     */
    public function setLocation(Request $request)
    {
        $this->validate($request, [
            'id' => 'nullable|integer|min:0'
        ]);
        $id = $request->input('id', 0);
        
        $data = [];
        if (! $id) {
            // 删除 session 内地址信息
            $this->location()
                ->unsetDistrict()
                ->save();
        } else {
            // 查询地址信息
            $districtService = new DistrictService();
            $data = $districtService->findSignByCity($id);
            // 保存地址信息到 session
            $this->location()
                ->setDistrict($data)
                ->save();
        }
        // 保存数据到 cookie
        (new CookieLocationEntity($this->location()))->save();
        
        return $this->response->setResponseData($data)->getResponse();
    }
}